package cn.iniche.utils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;


public final class EncryptUtils {

    private static final char[] HEX_DIGITS =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};


    @Nullable
    public static String getFileMd5(@NonNull File file) {
        try (DigestInputStream in = new DigestInputStream(
                new FileInputStream(file), MessageDigest.getInstance("MD5"))) {
            byte[] buffer = new byte[1024 * 256];
            while (true) if (in.read(buffer) == -1) break;
            return bytes2HexString(in.getMessageDigest().digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Nullable
    private static String bytes2HexString(final byte[] bytes) {
        if (bytes == null) return null;
        final char[] hexDigits = HEX_DIGITS;
        int len = bytes.length;
        if (len <= 0) return "";
        char[] ret = new char[len << 1];
        for (int i = 0, j = 0; i < len; i++) {
            ret[j++] = hexDigits[bytes[i] >> 4 & 0x0f];
            ret[j++] = hexDigits[bytes[i] & 0x0f];
        }
        return new String(ret);
    }


}
